﻿using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;

namespace MaterialTypeRecognition.Shell.AuthenticationServices.Permissions
{
    internal class PermissionHandler : AuthorizationHandler<PermissionRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionRequirement requirement)
        {
            var claim = context.User.FindFirst(claim => claim.Type == "Permission");

            if (claim is null)
            {
                context.Fail();
                return Task.CompletedTask;
            }

            if (claim.Value == UserPermissoins.Users.Admin)
            {
                // 无敌管理员。
                context.Succeed(requirement);
            }
            else
            if (claim.Value == UserPermissoins.Users.PE)
            {
                // PE 具有 OPN 或 OPN 班长权限。
                if (requirement is OPNMonitorPermissionRequirement || requirement is OPNPermissionRequirement || requirement is PEPermissionRequirement)
                    context.Succeed(requirement);
                else
                    context.Fail();
            }
            else
            if (claim.Value == UserPermissoins.Users.ME)
            {
                // ME 具有 OPN 或 OPN 班长权限。
                if (requirement is OPNMonitorPermissionRequirement || requirement is OPNPermissionRequirement || requirement is MEPermissionRequirement)
                    context.Succeed(requirement);
                else
                    context.Fail();
            }
            else
            if (claim.Value == UserPermissoins.Users.OPNMonitor)
            {
                // OPN 班长权限。
                if (requirement is OPNMonitorPermissionRequirement || requirement is OPNPermissionRequirement)
                    context.Succeed(requirement);
                else
                    context.Fail();
            }
            else
            if (claim.Value == UserPermissoins.Users.OPN)
            {
                // OPN 权限。
                if (requirement is OPNPermissionRequirement)
                    context.Succeed(requirement);
                else
                    context.Fail();
            }

            return Task.CompletedTask;
        }
    }
}
